const query = require('../../dbConfig/index')

const get = async (ctx,next)=>{
	const body = ctx.request.body
	const offset = (body.pageNumber - 1) * Number(body.pageSize);  
	let sql = 'SELECT * FROM rewards';  
	let params = [];  
	if (body.student_id) {  
		sql += sql.includes('WHERE')? ' and student_id=?': ' WHERE student_id=?';  
		params.push(body.student_id);  
	}
	if (body.classes_id) {  
		sql += sql.includes('WHERE')?  'and classes_id=?':' WHERE classes_id=?';  
		params.push(body.classes_id);  
	}else if(ctx.state.power!=1&&ctx.state.classes){
		let str = ctx.state.classes.split(",").map(num => parseInt(num))
		sql += sql.includes('WHERE')? ' and classes_id IN (?)':' WHERE classes_id IN (?)';  
		params.push(str); 
	}
	if (body.rewardsType) {  
		sql +=sql.includes('WHERE')? ' and rewards_type=?': ' WHERE rewards_type=?';  
		params.push(body.rewardsType);  
	}
	if (body.createtime) {  
		sql +=sql.includes('WHERE')? ' and createtime=?': ' WHERE createtime=?';  
		params.push(body.createtime);
	}
	  sql += ' LIMIT ? OFFSET ?';  
	  params.push(Number(body.pageSize));  
	  params.push(offset);
	const res = await query(sql,params)
	const total = await query(`SELECT COUNT(*) as total FROM rewards`)
	if(res.length>0){
		ctx.body={code:200,data:{records:res,total:total[0].total},msg:'成功'}
		next()
	}else{
		ctx.body={code:0,data:null,msg:'暂无奖惩信息'}
	}
}
const getItem = async (ctx,next)=>{
	const body = ctx.request.body 
	let sql = `SELECT * FROM rewards where student_id=${body.student_id}`  
	const res = await query(sql)
	if(res.length>0){
		ctx.body={code:200,data:res,msg:'成功'}
		next()
	}else{
		ctx.body={code:0,data:null,msg:'没有奖惩信息数据'}
	}
}
const updata = async (ctx,next)=>{
	const body = ctx.request.body
	await query(`UPDATE rewards SET student_id=?,student_name=?,classes_id=?,createtime=?,rewards_type=?,rewards_pic=?,rewards_description=? WHERE rewards_id='${body.rewards_id}'`,[body.student_id,body.student_name,body.classes_id,body.createtime,body.rewards_type,body.rewards_pic,body.rewards_description])
	ctx.body={code:200,data:null,msg:'成功'}
	next()
	
}
const add = async (ctx,next)=>{
	const body = ctx.request.body
	await query(`INSERT INTO rewards (student_id,student_name,classes_id,createtime,rewards_type,rewards_pic,rewards_description) VALUES (?,?,?,?,?,?,?)`,[body.student_id,body.student_name,body.classes_id,body.createtime,body.rewards_type,body.rewards_pic,body.rewards_description])
	ctx.body={code:200,data:null,msg:'成功'}
	next()
}
const remove = async (ctx,next)=>{
	const body = ctx.request.body
	await query(`DELETE FROM rewards WHERE rewards_id=${body.id}`)
	ctx.body={code:200,data:null,msg:'成功'}
	next()
}
module.exports = {
	get,getItem,
	add,updata,remove
}